/*************************************************************************
	> File Name: test8.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/09/19 20:18
 ************************************************************************/

#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <cassert>

static void showSig(sigset_t &pending)
{
    for (int sig = 1; sig <= 40; sig++) {
        if (sigismember(&pending, sig)) {
            std::cout << 1;
        } else {
            std::cout << 0;
        }
    }
    std::cout << std::endl;
}

int main(int argc, char *argv[])
{
    pid_t id = fork();
    if (id == -1) {
        perror("fork");
        exit(1);
    }
    if (id == 0) {
        std::cout << "Create child process success, pid:" << getpid() << std::endl;
        sigset_t bset, pending;
        sigemptyset(&bset);
        sigemptyset(&pending);
        sigaddset(&bset, 2);
        sigaddset(&bset, 40);
        int n = sigprocmask(SIG_BLOCK, &bset, nullptr);
        assert(n == 0);
        (void)n;
        while (1) {
            sigpending(&pending);
            showSig(pending);
            sleep(1);
        }
    } 
    std::cout << "Father process pid:" << getpid() << std::endl;
    std::cout << "Child process pid:" << id << std::endl;
    sleep(5);
    for (int i = 0; i < 5; ++i) {
        kill(id, 2);
    }
    for (int i = 0; i < 5; ++i) {
        kill(id, 40);
    }
    int status;
    waitpid(id, &status, 0);
    std::cout << "Child process exit code:" << (status & 0x7f) << std::endl;
    return 0;
}
